/**
 * 
 */
package cs342.project1.mathNotebook.PKI;

import java.math.BigInteger;
import java.security.Key;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAKey;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;

/** Shared functionality of both public and private SimpleRSAKeys
 * @author Aaron Heise
 *
 */
public abstract class SimpleRSAKey implements RSAKey, Key {
	private static KeyFactory keyFactory = null;
	protected Cipher rsa = null;
	
	protected SimpleRSAKey() {
		try {
			rsa = Cipher.getInstance("rsa");
		} catch (NoSuchAlgorithmException e) {
			throw new SimpleRSAAlgorithmException(e);
		} catch (NoSuchPaddingException e) {
			throw new SimpleRSAAlgorithmException(e);
		}
	}
	
	/** Give protected access to the underlying key.
	 * @return Returns the underlying key.
	 */
	protected abstract Key getKey();
	
	/* (non-Javadoc)
	 * @see java.security.Key#getAlgorithm()
	 */
	@Override
	public String getAlgorithm() {
		// TODO Auto-generated method stub
		return this.getKey().getAlgorithm();
	}

	/* (non-Javadoc)
	 * @see java.security.Key#getEncoded()
	 */
	@Override
	public byte[] getEncoded() {
		// TODO Auto-generated method stub
		return this.getKey().getEncoded();
	}

	/* (non-Javadoc)
	 * @see java.security.Key#getFormat()
	 */
	@Override
	public String getFormat() {
		// TODO Auto-generated method stub
		return this.getKey().getFormat();
	}

	/* (non-Javadoc)
	 * @see java.security.interfaces.RSAKey#getModulus()
	 */
	@Override
	public BigInteger getModulus() {
		// TODO Auto-generated method stub
		return ((RSAKey)this.getKey()).getModulus();
	}
	
	protected static KeyFactory getKeyFactory() throws SimpleRSAAlgorithmException {
		if(SimpleRSAKey.keyFactory == null) {
			try {
				SimpleRSAKey.keyFactory = KeyFactory.getInstance("rsa");
			} catch (NoSuchAlgorithmException e) {
				throw new SimpleRSAAlgorithmException("Could not find RSA algorithm", e);
			}
		}
		
		return SimpleRSAKey.keyFactory;
	}
}
